﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OL.FrameCore.Infrastructure.Utility
{
    /// <summary>
    /// 对象属性映射
    /// </summary>
    public class EntityMap
    {
        /// <summary>
        /// 对象属性映射
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T2 Map<T1, T2>(T1 t)
        {
            T2 result = System.Activator.CreateInstance<T2>();
            result = Map<T1, T2>(t, result);
            return result;
        }

        /// <summary>
        /// 对象属性映射
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T2 Map<T1, T2>(T1 t, T2 t2)
        {
            var propertys = t.GetType().GetProperties();
            foreach (var propertyInfo in propertys)
            {
                var pname = propertyInfo.Name;
                var value = propertyInfo.GetValue(t);
                if (value != null && t2.GetType().GetProperties().Any(c => c.Name == pname))
                {
                    t2.GetType().GetProperty(pname).SetValue(t2, value);
                }
            }
            return t2;
        }

        /// <summary>
        /// 对象属性映射
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T2 Map<T2>(object t)
        {
            return Map<object,T2>(t);

            //T2 t2 = System.Activator.CreateInstance<T2>();

            //var propertys = t.GetType().GetProperties();
            //foreach (var propertyInfo in propertys)
            //{
            //    var pname = propertyInfo.Name;
            //    var value = propertyInfo.GetValue(t);
            //    if (value != null && t2.GetType().GetProperties().Any(c => c.Name == pname))
            //    {
            //        t2.GetType().GetProperty(pname).SetValue(t2, value);
            //    }
            //}
            //return t2;
        }
    }
}
